<?php

namespace app\admin\controller;

use app\admin\logic\BranchLogic;

/**
 * 分部管理api控制器
 * Created by PhpStorm.
 * User: tyll
 * Date: 2019/09/17
 * Time: 09:51
 */
class Branch extends Base
{
    public function __construct()
    {
        parent::__construct();
        $this->b_logic = new BranchLogic();
    }

    /**
     * 获取分部
     * @return \think\response\Json
     */
    public function ajax_get_branch()
    {
        $params = input();
        $r = $this->check_admin_token($params);
        if ($r['code'] != 1) {
            return json($r);
        }

        $maps = $this->b_logic->get_search_branch_maps();
        $limit = ($params['page'] - 1) * $params['rows'];

        $list = model('branch')->get_list($maps, 'id,name', 'id desc', '', $limit, $params['rows']);

        $total_num = model('branch')->get_count($maps, 'id');

        $data['list'] = $list;
        $data['total_num'] = $total_num;
        return json($this->b_logic->get_response(1, 'OK', $data));
    }

    /**
     * 新增分部
     * @return \think\response\Json
     */
    public function ajax_add_branch()
    {
        $params = input();
        $r = $this->check_admin_token($params);
        if ($r['code'] != 1) {
            return json($r);
        }

        //检查新增分部规则
        $r = $this->b_logic->check_add_branch_rule($params);
        if (!$r['code']) {
            return json($r);
        }

        $b_data = [];
        $b_data['name'] = trim($params['name']);
        $r = model('branch')->insert($b_data);
        if ($r) {
            return json($this->b_logic->get_response(1, '新增成功'));
        }
        return json($this->b_logic->get_response(0, '新增失败'));
    }

    /**
     * 修改分部
     * @return \think\response\Json
     */
    public function ajax_save_branch()
    {
        $params = input();
        $r = $this->check_admin_token($params);
        if ($r['code'] != 1) {
            return json($r);
        }

        //检查修改分部规则
        $r = $this->b_logic->check_save_branch_rule($params);
        if (!$r['code']) {
            return json($r);
        }
        $b_detail = $r['data']['b_detail'];

        $b_data = [];
        $b_data['name'] = trim($params['name']);

        $maps = [];
        $maps[] = ['id', '=', $b_detail['id']];
        $r = model('branch')->force()->save($b_data, $maps);
        if ($r !== false) {
            return json($this->b_logic->get_response(1, '修改成功'));
        }
        return json($this->b_logic->get_response(0, '修改失败'));
    }

    /**
     * 删除分部
     * @return \think\response\Json
     */
    public function ajax_del_branch()
    {
        $params = input();
        $r = $this->check_admin_token($params);
        if ($r['code'] != 1) {
            return json($r);
        }

        $r = model('branch')->destroy($params['branchid']);
        if ($r) {
            return json($this->b_logic->get_response(1, '删除成功'));
        }
        return json($this->b_logic->get_response(0, '删除失败'));
    }
}
